<template>
  <div>
    <el-form :model="params" ref="ruleForm" label-position="right" size="small" label-width="110px" class="base-search-more">
      <el-row>
        <el-col :span="6" v-if="$store.state.showAgent">
          <el-form-item label="区域">
            <agent-list style="width: 100%" :agentids="params.agentIds" v-on:listenToChildEvent="getAentId" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="商家名称">
            <el-input style="width: 100%" placeholder="请输入内容" v-model="params.name" clearable></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="日期">
            <pt-date-picker v-model="params.date" :shortcuts="[{ text: '今天', start: 0, end: 0}, { text: '近七天', start: -7, end: 0}, {text: '近一个月', start: -30, end: 0}]" />
          </el-form-item>
        </el-col>
        <el-col :span="$store.state.showAgent? 6: 12" style="text-align: right;">
          <el-form-item label-width="0">
            <el-button @click="exportExcel()" v-loading="ExcelLoading">导出表格<i class="el-icon-download"></i></el-button>
            <el-button type="primary" size="small" icon="el-icon-search" @click="$refs.pagination1.handleSizeChange(10)">查询</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div class="base-table-wrap">
      <el-table :data="serialization(tableData.list)">
        <el-table-column label="商家名称" min-width="160" align="left">
          <template slot-scope="scope">
            <span @click="$refs.tableDetail.salesDetails(scope.row)" class="btn-bus">{{ scope.row.businessName }}</span>
          </template>
        </el-table-column>
        <el-table-column label="导出表格" min-width="100" align="left">
          <template slot-scope="scope">
            <el-button type="primary" size="mini" plain icon="el-icon-download" @click="downBusExit(scope.row)" />
          </template>
        </el-table-column>
        <el-table-column label="所属BD" prop="bdName" min-width="140" align="left" />
        <el-table-column prop="transactionAmount" min-width="120" align="right">
          <template slot="header" slot-scope="scope">
            <el-tooltip effect="dark" content="用户实际支付的金额" placement="top">
              <el-button icon="el-icon-question" type="text" />
            </el-tooltip>有效交易额
          </template>
        </el-table-column>
        <el-table-column prop="count1" min-width="120" align="right">
          <template slot="header" slot-scope="scope">
            <el-tooltip effect="dark" content="已完成的有效订单，支付后取消或其他全额退款的订单除外" placement="top">
              <el-button icon="el-icon-question" type="text" />
            </el-tooltip>有效订单量
          </template>
        </el-table-column>
        <el-table-column prop="goodsTotalSum" min-width="100" align="right">
          <template slot="header" slot-scope="scope">
            <el-tooltip effect="dark" content="有效订单内的商品数量" placement="top">
              <el-button icon="el-icon-question" type="text" />
            </el-tooltip>商品销量
          </template>
        </el-table-column>
        <el-table-column prop="originalPrice" min-width="150" align="right">
           <template slot="header" slot-scope="scope">
            <el-tooltip effect="dark" content="(商品原价+包装费)/原抽佣营业额" placement="top">
              <el-button icon="el-icon-question" type="text" />
            </el-tooltip>商品折前销售额
          </template>
        </el-table-column>
        <el-table-column prop="actualRakeTurnover" min-width="120" align="right">
          <template slot="header" slot-scope="scope">
            <el-tooltip effect="dark" content="（商品实付价格+包装费）≠实抽佣营业额（折前抽佣商家的实抽佣额和原抽佣额相同）" placement="top">
              <el-button icon="el-icon-question" type="text" />
            </el-tooltip>商品销售额
          </template>
        </el-table-column>
        <el-table-column prop="merchantDeliveryRevenue" min-width="130" align="right">
          <template slot="header" slot-scope="scope">
            <el-tooltip effect="dark" content="自配送费收益，不参与抽佣计算" placement="top">
              <el-button icon="el-icon-question" type="text" />
            </el-tooltip>商家配送盈收
          </template>
        </el-table-column>
        <el-table-column prop="merchantSubsidyAmount" min-width="130" align="right">
          <template slot="header" slot-scope="scope">
            <el-tooltip effect="dark" content="区域满减活动补贴商家承担部分+区域配送费活动补贴商家承担部分+首单立减活动补贴商家承担部分+商品特价支出+客户使用了的优惠券支出" placement="top">
              <el-button icon="el-icon-question" type="text" />
            </el-tooltip>商家活动支出
          </template>
        </el-table-column>
        <el-table-column prop="coefficient" min-width="100" align="right">
          <template slot="header" slot-scope="scope">
            <el-tooltip effect="dark" content="平台抽佣比例" placement="top">
              <el-button icon="el-icon-question" type="text" />
            </el-tooltip>抽佣比例
          </template>
          <template slot-scope="scope">{{scope.row.coefficient}}%</template>
        </el-table-column>
        <el-table-column prop="serviceFee" min-width="90" align="right">
          <template slot="header" slot-scope="scope">
            <el-tooltip effect="dark" content="即实抽佣盈收，区分折前折后" placement="top">
              <el-button icon="el-icon-question" type="text" />
            </el-tooltip>服务费
          </template>
        </el-table-column>
        <el-table-column prop="merchantRevenue" min-width="100" align="right">
          <template slot="header" slot-scope="scope">
            <el-tooltip effect="dark" content="商品折前销售额+商家自配送盈收-商家活动支出-服务费" placement="top">
              <el-button icon="el-icon-question" type="text" />
            </el-tooltip>商家收入
          </template>
        </el-table-column>
        <el-table-column prop="originalDistributionIncome" min-width="150" align="right">
          <template slot="header" slot-scope="scope">
            <el-tooltip effect="dark" content="有效订单内所有的配送费之和，不计入配送类优惠" placement="top">
              <el-button icon="el-icon-question" type="text" />
            </el-tooltip>区域原配送盈收
          </template>
        </el-table-column>
        <el-table-column prop="realDistributionSurplus" min-width="150" align="right">
          <template slot="header" slot-scope="scope">
            <el-tooltip effect="dark" content="用户支付的配送费，即有效订单内所有实际收取的配送费之和" placement="top">
              <el-button icon="el-icon-question" type="text" />
            </el-tooltip>区域实配送盈收
          </template>
        </el-table-column>
        <el-table-column prop="platformSubsidyAmount" min-width="140" align="right">
          <template slot="header" slot-scope="scope">
            <el-tooltip effect="dark" content="区域满减活动补贴代理商承担部分+区域配送费活动补贴代理商承担部分+首单立减活动补贴代理商承担部分+客户使用了的代理商红包" placement="top">
              <el-button icon="el-icon-question" type="text" />
            </el-tooltip>区域活动支出
          </template>
        </el-table-column>
        <el-table-column prop="riderTakeawayCommission" min-width="140" align="right">
          <template slot="header" slot-scope="scope">
            <el-tooltip effect="dark" content="1.配送费距离小于基础配送费距离：基本配送提出+特殊时段提成。2.超出基础距离：基础配送提出+超出距离部分提成+特殊时段提成。3.如果1和2计算结果大于每单最高提成，则按照每单最高提成计算" placement="top">
              <el-button icon="el-icon-question" type="text" />
            </el-tooltip>骑手外卖佣金
          </template>
        </el-table-column>
        <el-table-column prop="regionalGossPofit" min-width="120" align="right">
          <template slot="header" slot-scope="scope">
            <el-tooltip effect="dark" content="服务费+区域原配送费盈收-区域活动补贴" placement="top">
              <el-button icon="el-icon-question" type="text" />
            </el-tooltip>区域毛利润
          </template>
        </el-table-column>
        <el-table-column prop="regionalNetProfit" min-width="120" align="right">
          <template slot="header" slot-scope="scope">
            <el-tooltip effect="dark" content="服务费+区域原配送费盈收-区域活动补贴-骑手外卖佣金" placement="top">
              <el-button icon="el-icon-question" type="text" />
            </el-tooltip>区域净利润
          </template>
        </el-table-column>
        <el-table-column prop="cashWithdrawal" label="已提现金额" min-width="110" align="right"/>
        <el-table-column prop="expectIncome" label="未提现金额" min-width="110" align="right"/>
        <el-table-column prop="refundAmount" label="退款金额" min-width="100" align="right"/>
      </el-table>
      <pt-table-loading v-show="isloadingTable" />
      <pt-pagination ref="pagination1" :total="tableData.total" @listeningEvent="triggerEvent" />
    </div>
    <table-detail @downExlc="downExlc" :date="params.date" ref="tableDetail" />
    
    <el-table v-show="false" :data="ExTableData" :summary-method="getSummaries" show-summary id="out-table">  <!--不显示的表格下载-->
      <el-table-column prop="businessId" label="商家编号"/>
      <el-table-column prop="agentName" label="区域名称" />
      <el-table-column label="商家名称">
        <template slot-scope="scope">
          <span class="btn-bus">{{scope.row.businessName}}</span>
        </template>
      </el-table-column>
      <el-table-column label="所属BD" prop="bdName" />
      <el-table-column prop="transactionAmount" label="交易额" />
      <el-table-column prop="count1" label="有效订单量" />
      <el-table-column prop="goodsTotalSum" label="商品销量" />
      <el-table-column prop="originalPrice" label="商品折前销售额" />
      <el-table-column prop="actualRakeTurnover" label="商品销售额" />
      <el-table-column prop="merchantDeliveryRevenue" label="商家配送盈收" />
      <el-table-column prop="merchantSubsidyAmount" label="商家活动支出" />
      <el-table-column label="抽佣比例">
        <template slot-scope="scope">{{scope.row.coefficient}}%</template>
      </el-table-column>
      <el-table-column prop="serviceFee" label="服务费" />
      <el-table-column prop="merchantRevenue" label="商家收入" />
      <el-table-column prop="originalDistributionIncome" label="区域原配送盈收" />
      <el-table-column prop="realDistributionSurplus" label="区域实配送盈收" />
      <el-table-column prop="platformSubsidyAmount" label="区域活动支出" />
      <el-table-column prop="riderTakeawayCommission" label="骑手外卖佣金" />
      <el-table-column prop="regionalNetProfit" label="区域净利润" />
      <el-table-column prop="cashWithdrawal" label="已提现金额" />
      <el-table-column prop="expectIncome" label="未提现金额" />
      <el-table-column prop="refundAmount" label="退款金额" />
    </el-table>
    <table border v-show="false" v-html="tableStr" id="shopTable"></table>
  </div>
</template>

<script>
  import FileSaver from 'file-saver'
  import XLSX from 'xlsx'
  import acction from '@/utils/acction.js'
  import { getDay } from '@/utils/ptkc.js'
  import { exportExcelMethod } from '@/utils/exportExcel.js'
  import { ukBusinessMoney } from '@/api/finance.js'
  import tableDetail from './components/salesDetail'
  export default {
    components: { tableDetail },
    data() {
      return {
        showDetails: false,
        params: {//查询数据
          page: 0,
          size: 10,
          name: '',
          date: [getDay(-30) + ' ' + '00:00:00', getDay(0) + ' ' + '23:59:59'],
          isdelive: 1,
          agentIds: [],//区域
        },
        isloadingTable: false,
        ExcelLoading: false,
        ExTableData: [], //表格数据
        tableData: {}, //表单数据
        total: null,
        tableStr: '' // 商家订单详情
      }
    },
    methods: {
      getAentId(item) { //获取子组件传递的区域
        this.params.agentIds = item
      },
      getTableList() {
        const params = { ...this.params }
        params.createtime1 = params.date?params.date[0] : ''
        params.createtime2 = params.date?params.date[1] : ''
        delete params.date
        params.agentIds = params.agentIds.length > 0 ? params.agentIds.join(',') : ''
        this.isloadingTable = true
        this.$http.get('/server/business/dirbusinessmoney1?' + this.qs.stringify(params)).then(res => {
          if (res.data.success) {
            this.tableData = res.data.data
            this.total = res.data.data.total
          }
        }).finally(() => { this.isloadingTable = false })
      },
      serialization(arr) { // 序列化数组null转0
        const newArr = []
        if (arr && arr.length) {
          for (let i = 0; i< arr.length; i++) {
            const obj = {}
            for (const key in arr[i]) {
              if (key === 'businessName' || key === 'businessId' ||
               key === 'businessDeliver' ||key === 'agentName' ||
               key === 'businessCreateTime' || key === 'bdName') {
                obj[key]= arr[i][key] || ''
              } else if (key === 'goodsTotalSum' || key === 'count1'){
                obj[key]= arr[i][key] ? arr[i][key] : '0'
              } else if (key === 'coefficient') {
                obj[key]= arr[i][key] || '0'
              } else {
                obj[key] = arr[i][key] ? arr[i][key].toFixed(2) : '0.00'
              }
            }
            newArr.push(obj)
          }
        }
        return newArr
      },
      getSummaries(param) { // 表格统计
        const {columns, data} = param
        const sums = []
        columns.forEach((column, index) => {
          if (index === 0) {
            sums[index] = '总计'
            return
          }
          const values = data.map(item => Number(item[column.property]))
          if (!values.every(value => isNaN(value))) {
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr)
              if (!isNaN(value)) {
                return new acction(prev,curr).accAdd()
              } else {
                return prev
              }
            }, 0)
          } else {
            sums[index] = 'N/A'
          }
        })
        return sums
      },
      downExlc(el, name) {
        const wb = XLSX.utils.table_to_book(el)
        const wbout = XLSX.write(wb, {bookType: 'xlsx', bookSST: true, type: 'array'})
        try {
          FileSaver.saveAs(new Blob([wbout], {type: 'application/octet-stream'}), `${name}.xls`)
        } catch (e) {
        
        }
        return wbout
      },
      exportExcel() { // 导出表格
        this.ExcelLoading = true
        const params = { ...this.params }
        params.createtime1 = params.date?params.date[0] : ''
        params.createtime2 = params.date?params.date[1] : ''
        params.agentIds = params.agentIds.length > 0 ? params.agentIds.join(',') : ''
        params.page = 0
        params.size = this.total
        delete params.date
        this.$http.get('/server/business/dirbusinessmoney1?' + this.qs.stringify(params)).then(res => {
          if (res.data.success) {
            this.ExTableData = this.serialization(res.data.data.list)
            setTimeout(() => {
              this.ExcelLoading = false
              var wb = XLSX.utils.table_to_book(document.querySelector('#out-table'))
              var wbout = XLSX.write(wb, {bookType: 'xlsx', bookSST: true, type: 'array'})
              try {
                FileSaver.saveAs(new Blob([wbout], {type: 'application/octet-stream'}), `${params.createtime1.slice(0,10)}-${params.createtime2.slice(0,10)}.xls`)
              } catch (e) {
              }
              return wbout
            }, 500)
          }
        }).finally(() => { this.ExcelLoading = false })
      },
      triggerEvent(type,val) { // 分页器
        if (type === 'page') {
          this.params.page = val - 1
        } else if (type === 'size') {
          this.params.page = 0
          this.params.size = val
        }
        this.getTableList()
      },
      downBusExit(row) {
        const params = {
          businessId: row.businessId,
          createtime1: this.params.date[0],
          createtime2: this.params.date[1]
        }
        ukBusinessMoney(params).then(res => {
          if (res.success) {
            this.tableToExit(params, res.data)
          }
        })
      },
      tableToExit(params, data) {
        const busInfo = data.summary
        const table = `<tr><th colspan="4" style="width: 240px;">invoice no.234234234</th><th colspan="3" style="width:150px;">ZZ Delivery</th></tr>
          <tr><td colspan="4">${busInfo.name}</td><td colspan="3">FILL YOUR HUNGER TECHNOLOGY LTD</td></tr>
          <tr><td colspan="4">${busInfo.provinceName+busInfo.address}</td><td colspan="3">5th Floor Queensgate, Suffolk Street Queensway</td></tr>
          <tr><td colspan="4"></td><td colspan="3" style="text-align:right">Birmingham</td></tr>
          <tr><td colspan="4"></td><td colspan="3" style="text-align:right">B1 1LX</td></tr>
          <tr><td colspan="7"></td></tr>
          <tr><td colspan="4"></td><td colspan="3" style="text-align:right">Tel:01212887688</td></tr>
          <tr><td colspan="4"></td><td colspan="3" style="text-align:right">Moble:07419829118</td></tr>
          <tr><td colspan="7"></td></tr>
          <tr><td colspan="7"></td></tr>
          <tr><td colspan="4"></td><td colspan="3" style="text-align:right">${new Date().toLocaleString()}</td></tr>
          <tr><td colspan="7"></td></tr>
          <tr><td colspan="7"></td></tr>
          <tr><td colspan="4">${data.startTime} - ${data.endTime}</td><td colspan="3"></td></tr>
          <tr><td colspan="4">Commission on Gross Order Value of（VAT@${busInfo.vatrate || 0}%)</td><td colspan="3" style="text-align:right">${busInfo.serviceFee }</td></tr>
          <tr><td colspan="4">admin fee</td><td colspan="3" style="text-align:right">${busInfo.ukServiceFeeTotal}</td></tr>
          <tr><td colspan="4">Subtotal</td><td colspan="3" style="text-align:right">${busInfo.subtotal}</td></tr>
          <tr><td colspan="4">VAT</td><td colspan="3" style="text-align:right">${busInfo.ukVatTotal}</td></tr>
          <tr><td colspan="4">Total Inc.VAT</td><td colspan="3" style="text-align:right">${busInfo.TotalIncVAT}</td></tr>
          <tr><td colspan="7"></td></tr>
          <tr><td colspan="7">Your statement</td></tr>
          <tr><td colspan="4">Total Sales in this period</td><td colspan="3" style="text-align:right">${busInfo.businessPayTotal}</td></tr>
          <tr><td colspan="4">service charge</td><td colspan="3" style="text-align:right">${busInfo.packingTotal}</td></tr>
          <tr><td colspan="4">ZZ Delivery Invoice</td><td colspan="3" style="text-align:right">${busInfo.agentTotal}</td></tr>
          <tr><td colspan="4">ZZ Delivery pay you</td><td colspan="3" style="text-align:right">${busInfo.businessTotal}</td></tr>
          <tr><td colspan="7"></td></tr>
          <tr><td colspan="7">Order Details</td></tr>
          <tr><td>序号</td><td>日期</td><td>单号</td><td>菜品原价总金额</td><td>商家折扣金额</td><td>配送费</td><td>实际价格</td></tr>`
        let str = ''
        let num1 = 0
        let num2 = 0
        let num3 = 0
        let num4 = 0
        for (let i = 0; i < data.list.length; i++) {
          const sum = new acction(data.list[i].originalRakeTurnoverCondition, data.list[i].ukServiceFee).accSub()
          str += `<tr>
            <td>${i+1}</td>
            <td>${data.list[i].createTime}</td>
            <td>${data.list[i].orderCode}</td>
            <td>${sum}</td>
            <td>${data.list[i].merchantSubsidyAmountCondition}</td>
            <td>${data.list[i].ukServiceFee}</td>
            <td>${data.list[i].businesspay}</td>
          </tr>`
          num1 = new acction(num1, sum).accAdd()
          num2 = new acction(num2, data.list[i].merchantSubsidyAmountCondition).accAdd()
          num3 = new acction(num3, data.list[i].businesspay).accAdd()
          num4 = new acction(num4, data.list[i].ukServiceFee).accAdd()
        }
        this.tableStr = table + str + `<tr><td colspan="3" style="text-align:left">合计</td><td>${num1}</td><td>${num2}</td><td>${num4}</td><td>${num3}</td></tr>`
        setTimeout(() => {
          const xlxsName = `${busInfo.name + params.createtime1.slice(0,10)}-${params.createtime2.slice(0,10)}.xls`
          exportExcelMethod('shopTable', xlxsName, 'sheet1')
        }, 500)
      }
    },
    mounted() {
      this.getTableList()
    }
  }
</script>

<style lang="scss" scoped>
  .btn-bus{
    color:$--color-primary;
    cursor: pointer;
  }
</style>
